<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\common\model\UserAddress;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 订单管理接口
 */
class Order extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = [];
    // 无需鉴权的接口
    protected $noNeedRight = ['*'];
    
    
    /**
     * 创建订单
     *
     * @ApiMethod (POST)
     * @ApiParams (name="product_id", type="integer", required=true, description="商品ID")
     * @ApiParams (name="sku_id", type="integer", required=true, description="SKU ID")
     * @ApiParams (name="quantity", type="integer", required=true, description="购买数量")
     * @ApiParams (name="address_id", type="integer", required=true, description="收货地址ID")
     * @ApiParams (name="pay_type", type="integer", required=true, description="支付方式：1=微信支付，2=支付宝支付，3=余额支付，4=权益积分支付，5=绿色积分支付")
     * @ApiParams (name="attribute_type", type="integer", required=true, description="商品类型：0=普通商品，1=权益商品，2=积分商品，3=助农抢购商品")
     * @ApiParams (name="session_id", type="integer", required=false, description="场次ID（助农抢购商品必传）")
     * @ApiParams (name="remark", type="string", required=false, description="订单备注")
     */
    public function submit()
    {
        $params = $this->request->post();
        
        $validate = new Validate([
            'product_id' => 'require|integer|gt:0',     // 商品ID
            'sku_id' => 'require|integer|gt:0',         // SKU ID
            'quantity' => 'require|integer|gt:0',       // 购买数量
            'address_id' => 'require|integer|gt:0',     // 地址ID
            'pay_type' => 'require|integer|egt:1|elt:5', // 支付方式：1-5
            'attribute_type' => 'require|integer|egt:1|elt:3', // 商品类型：1=权益商品，2=积分商品，3=助农抢购商品
            'session_id' => 'integer|gt:0',             // 场次ID
            'remark' => 'max:255',
        ]);
        
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        
        $user_id = $this->auth->id;
        
        // 获取商品属性类型和支付类型
        $attributeType = intval($params['attribute_type']);
        $payType = intval($params['pay_type']);
        
        // 助农抢购商品必须传入场次ID
        if ($attributeType == 3 && empty($params['session_id'])) {
            $this->error('助农抢购商品必须传入场次ID');
        }
        
        // 首先验证支付方式是否符合商品类型要求
        $this->validatePaymentType($attributeType, $payType);
        
        Db::startTrans();
        try {
            // 检查地址是否存在
            $address = UserAddress::where('id', $params['address_id'])
                ->where('user_id', $user_id)
                ->find();
   
            if (!$address) {
                $this->error('收货地址不存在');
            }
            
            // 获取商品信息
            $product = Db::name('product')
                ->where('id', $params['product_id'])
                ->where('shelf_status', 1)
                ->find();
              
            if (!$product) {
                $this->error('商品不存在或已下架');
            }
            
            // 初始化价格变量
            $price = 0;
            
            $productName = $product['name'];
            $productImage = $product['main_image'];
            
            // 获取SKU信息（现在sku_id是必传参数）
            $sku = Db::name('product_sku')
                ->field('id, sku_name, price, stock')
                ->where('id', $params['sku_id'])
                ->where('product_id', $params['product_id'])
                ->find();
             
            if (!$sku) {
                $this->error('商品规格不存在');
            }
            
            // 检查库存（根据商品类型处理不同的库存逻辑）
            if ($attributeType == 3) {
                // 助农抢购商品，需要检查场次和抢购库存
                $sessionId = intval($params['session_id']);
                
                // 验证场次是否存在且有效
                $session = Db::name('agriculture_flash_sale')
                    ->where('id', $sessionId)
                    ->where('status', 1) // 场次状态：1=有效
                    ->find();
                  
                if (!$session) {
                    $this->error('抢购场次不存在或已失效');
                }
                
                // 检查场次时间是否有效
                $currentTime = time();
                if ($currentTime < $session['start_time'] || $currentTime > $session['end_time']) {
                    $this->error('当前不在抢购时间内');
                }
                
                // 检查商品是否在该场次中
                $flashProduct = Db::name('agriculture_flash_sale_product')
                    ->where('product_id', $params['product_id'])
                    ->where('product_sku_id', $params['sku_id'])
                    ->where('flash_sale_id', $sessionId)
                    ->find();
                 
                if (!$flashProduct) {
                    $this->error('该商品不在当前抢购场次中');
                }
                
                if ($flashProduct['stock'] < $params['quantity']) {
                    $this->error('抢购商品库存不足');
                }
                
                // 使用抢购价格
                $price = $flashProduct['flash_price'];
            } else {
                // 普通商品检查SKU库存
                if ($sku['stock'] < $params['quantity']) {
                    $this->error('商品库存不足');
                }
            }
            
            // 对于非助农抢购商品，查询SKU对应的属性价格
            if ($attributeType != 3) {
                $skuAttributePrice = Db::name('product_attribute_price')
                    ->where('product_id', $params['product_id'])
                    ->where('sku_id', $sku['id'])
                    ->where('attribute_type', $attributeType)
                    ->find();
                
                // 如果没有找到SKU对应的属性价格，则查询该商品的默认属性价格
                if (!$skuAttributePrice) {
                    $skuAttributePrice = Db::name('product_attribute_price')
                        ->where('product_id', $params['product_id'])
                        ->where('attribute_type', $attributeType)
                        ->where('sku_id', 0)
                        ->find();
                }
                
                // 如果找到属性价格，则使用该价格，否则使用SKU价格
                $price = $skuAttributePrice ? $skuAttributePrice['price'] : $sku['price'];
            }
            
            // 确保价格不为0（积分商品使用绿色积分支付时价格可以为0）
            if ($price <= 0 && !($attributeType == 2 && $payType == 5)) {
                $this->error('商品价格无效，请联系客服');
            }
            
            // 设置SKU信息
            $skuName = $sku['sku_name'] ?? '';
            $skuId = $sku['id'];
            
            // 更新商品销量
            Db::name('product')
                ->where('id', $product['id'])
                ->setInc('sales', $params['quantity']);
            
            
            // 计算商品总价和支付金额
            if ($payType == 5) {
                // 获取积分商品配置
                $pointsProduct = Db::name('product_attribute_price')
                    ->where('product_id', $params['product_id'])
                    ->where('attribute_type', 2)
                    ->find();
                    
                if (!$pointsProduct) {
                    throw new Exception('积分商品配置不存在');
                }
                
                // 计算所需积分
                $requiredPoints = $pointsProduct['points'] * $params['quantity'];
                $totalAmount = $requiredPoints;
                $payAmount = $requiredPoints;
                $freightAmount = 0;

            } elseif ($payType == 4) {
                // 权益积分支付 1:1
                $totalAmount = $price * $params['quantity'];
                $freightAmount = 0;
                $payAmount = $totalAmount + $freightAmount;

            } else {
                // 零钱支付
                $totalAmount = $price * $params['quantity'];
                $freightAmount = 0;
                $payAmount = $totalAmount + $freightAmount;
            }
            
            // 生成订单号
            $orderNo = date('YmdHis') . mt_rand(1000, 9999) . $user_id;
            
            // 根据支付方式确定订单状态
            // 积分支付（权益积分4、绿色积分5）：已支付状态1
            // 其他支付方式（微信1、支付宝2、聚合支付3）：待支付状态0
            $orderStatus = ($payType == 4 || $payType == 5) ? 1 : 0;
            
            // 创建订单
            $orderData = [
                'order_no' => $orderNo,
                'user_id' => $user_id,
                'merchant_id' => $product['merchant_id'],
                'address_id' => $params['address_id'],
                'address' => json_encode([
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'district' => $address['district'],
                    'address' => $address['address']
                ]),
                'total_amount' => $totalAmount,
                'pay_amount' => $payAmount,
                'discount_amount' => 0,
                'pay_type' => $payType,
                'attribute_type' => $attributeType,
                'order_status' => $orderStatus,
                'remark' => isset($params['remark']) ? $params['remark'] : '',
                'createtime' => time(),
                'updatetime' => time()
            ];
            
            // 如果是助农抢购商品，添加场次ID
            if ($attributeType == 3) {
                $orderData['session_id'] = intval($params['session_id']);
            }
            
            $orderId = Db::name('order')->insertGetId($orderData);
            
            // 创建订单商品
            $itemPrice = $price;
            if ($payType == 5) {
                $itemPrice = $totalAmount / $params['quantity'];
            }
            
            Db::name('order_item')->insert([
                'order_id' => $orderId,
                'product_id' => $product['id'],
                'sku_id' => $skuId,
                'product_name' => $productName,
                'sku_name' => $skuName,
                'image' => $productImage,
                'price' => $itemPrice,
                'quantity' => $params['quantity'],
                'total_amount' => $totalAmount,
                'createtime' => time(),
                'updatetime' => time()
            ]);
            
            // 如果是权益商品，处理积分分配逻辑
            if ($attributeType == 1) {
                $totalPoints = intval($totalAmount);
                
                if ($totalPoints > 0) {
                    // 90%积分进入用户积分账户
                    $balancePoints = intval($totalPoints * 0.9);
                    
                    // 10%积分锁定为权益证书
                    $certificatePoints = $totalPoints - $balancePoints;
                    
                    // 更新用户积分
                    User::score($balancePoints, $user_id, '购买权益商品'.$productName.'获得');
                    
                    // 创建权益证书
                    Db::name('user_equity_certificate')->insert([
                        'user_id' => $user_id,
                        'product_id' => $product['id'],
                        'order_id' => $orderId,
                        'points' => $totalPoints,
                        'locked_points' => $certificatePoints,
                        'status' => 1,
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);
                    
                    // 记录权益积分日志
                    Db::name('user_equity_log')->insert([
                        'user_id' => $user_id,
                        'points' => $totalPoints,
                        'before' => 0,
                        'after' => $totalPoints,
                        'memo' => '购买id为'.$orderId.'的权益商品'.$productName.'获得积分',
                        'createtime' => time()
                    ]);
                }
            }
            
            // 如果是积分商品，处理积分扣除逻辑
            if ($attributeType == 2 && $payType == 5) {
                $requiredPoints = $totalAmount;
                
                // 检查用户积分是否足够
                $userInfo = Db::name('user')->where('id', $user_id)->find();
                if ($userInfo['green_score'] < $requiredPoints) {
                    $this->error('绿色积分不足，无法购买');
                }
                
                // 扣除用户绿色积分
                User::green_score(-$requiredPoints, $user_id, '购买积分商品'.$productName.'扣除');
                
                // 记录积分商品购买日志
                Db::name('user_points_log')->insert([
                    'user_id' => $user_id,
                    'product_id' => $product['id'],
                    'order_id' => $orderId,
                    'points' => $requiredPoints,
                    'type' => 'consume',
                    'memo' => '购买积分商品'.$productName,
                    'createtime' => time()
                ]);
            }

            // 如果是助农商品，使用权益积分支付，处理权益积分扣除逻辑
            if ($attributeType == 3 && $payType == 4) {
                // 计算需要扣除的权益积分（1:1比例）
                $requiredEquityPoints = intval($totalAmount);
                
                // 检查用户权益积分是否足够
                $userInfo = Db::name('user')->where('id', $user_id)->find();
                if ($userInfo['score'] < $requiredEquityPoints) {
                    $this->error('权益积分不足，无法购买');
                }
                
                // 扣除用户权益积分
                User::score(-$requiredEquityPoints, $user_id, '购买助农商品'.$productName.'扣除');
                
                // 记录权益积分消费日志
                Db::name('user_equity_log')->insert([
                    'user_id' => $user_id,
                    'points' => -$requiredEquityPoints,
                    'before' => $userInfo['score'],
                    'after' => $userInfo['score'] - $requiredEquityPoints,
                    'memo' => '购买助农商品'.$productName.'消费',
                    'createtime' => time()
                ]);
            }
            
            // 扣减库存（只有积分支付才立即扣减，微信/支付宝等需要在支付回调后扣减）
            if ($payType == 4 || $payType == 5) {
                if ($attributeType == 3) {
                    // 助农抢购商品扣减抢购库存
                    Db::name('agriculture_flash_sale_product')
                        ->where('product_id', $params['product_id'])
                        ->where('product_sku_id', $params['sku_id'])
                        ->where('flash_sale_id', intval($params['session_id']))
                        ->setDec('stock', $params['quantity']);
                } else {
                    // 普通商品扣减SKU库存
                    Db::name('product_sku')
                        ->where('id', $params['sku_id'])
                        ->setDec('stock', $params['quantity']);
                }
            }
            
            Db::commit();
            
            // 返回订单信息
            $this->success('订单创建成功', [
                'order_id' => $orderId,
                'order_no' => $orderNo,
                'pay_amount' => number_format($payAmount, 2, '.', ''),
                'is_equity' => $attributeType == 1 ? 1 : 0, // 是否为权益商品
                'is_points' => $attributeType == 2 ? 1 : 0, // 是否为积分商品
                'attribute_type' => $attributeType // 商品类型
            ]);
            
        } catch (Exception $e) {
            Db::rollback();
            Log::error('创建订单失败: ' . $e->getMessage());
            $this->error('系统错误，请稍后重试');
        }
    }
    
    /**
     * 获取订单列表
     *
     * @ApiMethod (POST)
     * @ApiParams (name="status", type="integer", required=false, description="订单状态：0=全部，1=待付款，2=待发货，3=待收货，4=已完成，5=已取消")
     * @ApiParams (name="page", type="integer", required=false, description="页码")
     * @ApiParams (name="limit", type="integer", required=false, description="每页数量")
     */
    public function lists()
    {
        $user_id = $this->auth->id;
        $status = $this->request->post('status', 0);
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        
        // 构建查询条件
        $where = [
            'user_id' => $user_id
        ];
        
        // 根据状态筛选
        if ($status) {
            switch ($status) {
                case 1: // 待付款
                    $where['order_status'] = 0;
                    break;
                case 2: // 待发货
                    $where['order_status'] = 1;
                    break;
                case 3: // 待收货
                    $where['order_status'] = 2;
                    break;
                case 4: // 已完成
                    $where['order_status'] = 3;
                    break;
                case 5: // 已取消
                    $where['order_status'] = 4;
                    break;
            }
        }
        
        // 查询订单列表
        $orders = Db::name('order')
            ->where($where)
            ->order('createtime desc')
            ->page($page, $limit)
            ->select();
        
        // 获取订单总数
        $total = Db::name('order')
            ->where($where)
            ->count();
        
        // 获取订单商品信息
        $orderIds = array_column($orders, 'id');
        $orderItems = [];
        
        if ($orderIds) {
            $items = Db::name('order_item')
                ->where('order_id', 'in', $orderIds)
                ->select();
            
            // 按订单ID分组
            foreach ($items as $item) {
                $orderItems[$item['order_id']][] = $item;
            }
        }
        
        // 处理订单数据
        $orderStatusMap = [
            0 => '待付款',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成',
            4 => '已取消',
            5 => '已退款'
        ];
        
        $payTypeMap = [
            0 => '未支付',
            1 => '微信支付',
            2 => '支付宝支付',
            3 => '余额支付',
            4 => '权益积分支付',
            5 => '绿色积分支付'
        ];
        
        $attributeTypeMap = [
            1 => '权益商品',
            2 => '积分商品',
            3 => '助农商品'
        ];
        
        $result = [];
        foreach ($orders as $order) {
            $orderData = [
                'id' => $order['id'],
                'order_no' => $order['order_no'],
                'total_amount' => $order['total_amount'],
                'pay_amount' => $order['pay_amount'],
                'order_status' => $order['order_status'],
                'order_status_text' => isset($orderStatusMap[$order['order_status']]) ? $orderStatusMap[$order['order_status']] : '未知状态',
                'pay_type' => $order['pay_type'],
                'pay_type_text' => isset($payTypeMap[$order['pay_type']]) ? $payTypeMap[$order['pay_type']] : '未知支付方式',
                'attribute_type' => $order['attribute_type'],
                'attribute_type_text' => isset($attributeTypeMap[$order['attribute_type']]) ? $attributeTypeMap[$order['attribute_type']] : '未知商品类型',
                'createtime' => date('Y-m-d H:i:s', $order['createtime']),
                'items' => []
            ];
            
            // 添加订单商品信息
            if (isset($orderItems[$order['id']])) {
                foreach ($orderItems[$order['id']] as $item) {
                    $orderData['items'][] = [
                        'id' => $item['id'],
                        'product_id' => $item['product_id'],
                        'product_name' => $item['product_name'],
                        'sku_id' => $item['sku_id'],
                        'sku_name' => $item['sku_name'],
                        'image' => $item['image'],
                        'price' => $item['price'],
                        'quantity' => $item['quantity'],
                        'total_amount' => $item['total_amount']
                    ];
                }
            }
            
            $result[] = $orderData;
        }
        
        $this->success('获取成功', [
            'total' => $total,
            'per_page' => intval($limit),
            'current_page' => intval($page),
            'last_page' => ceil($total / $limit),
            'data' => $result
        ]);
    }
    
    /**
     * 获取订单详情
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="订单ID")
     */
    public function detail()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('id');
        
        if (!$order_id) {
            $this->error('订单ID不能为空');
        }
        
        // 查询订单信息
        $order = Db::name('order')
            ->where('id', $order_id)
            ->where('user_id', $user_id)
            ->find();
        
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 查询订单商品
        $items = Db::name('order_item')
            ->where('order_id', $order_id)
            ->select();
        
        // 解析收货地址
        $address = json_decode($order['address'], true);
        $addressText = '';
        if ($address) {
            $addressText = $address['province'] . ' ' . $address['city'] . ' ' . $address['district'] . ' ' . $address['address'];
        }
        
        // 获取收货人信息
        $receiver = [];
        $userAddress = Db::name('user_address')
            ->where('id', $order['address_id'])
            ->find();
        
        if ($userAddress) {
            $receiver = [
                'name' => $userAddress['name'],
                'mobile' => $userAddress['mobile'],
                'address' => $addressText
            ];
        } else {
            // 如果地址已删除，使用订单中保存的地址信息
            $receiver = [
                'name' => '',
                'mobile' => '',
                'address' => $addressText
            ];
        }
        
        // 订单状态和支付方式映射
        $orderStatusMap = [
            0 => '待付款',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成',
            4 => '已取消',
            5 => '已退款'
        ];
        
        $payTypeMap = [
            0 => '未支付',
            1 => '微信支付',
            2 => '支付宝支付',
            3 => '余额支付',
            4 => '权益积分支付',
            5 => '绿色积分支付'
        ];
        
        $attributeTypeMap = [
            1 => '权益商品',
            2 => '积分商品',
            3 => '助农商品'
        ];
        
        // 处理订单商品信息
        $orderItems = [];
        foreach ($items as $item) {
            $orderItems[] = [
                'id' => $item['id'],
                'product_id' => $item['product_id'],
                'product_name' => $item['product_name'],
                'sku_id' => $item['sku_id'],
                'sku_name' => $item['sku_name'],
                'image' => $item['image'],
                'price' => $item['price'],
                'quantity' => $item['quantity'],
                'total_amount' => $item['total_amount']
            ];
        }
        
        // 构建订单详情数据
        $result = [
            'id' => $order['id'],
            'order_no' => $order['order_no'],
            'total_amount' => $order['total_amount'],
            'pay_amount' => $order['pay_amount'],
            'freight_amount' => 0, // 运费
            'discount_amount' => $order['discount_amount'],
            'order_status' => $order['order_status'],
            'order_status_text' => isset($orderStatusMap[$order['order_status']]) ? $orderStatusMap[$order['order_status']] : '未知状态',
            'pay_type' => $order['pay_type'],
            'pay_type_text' => isset($payTypeMap[$order['pay_type']]) ? $payTypeMap[$order['pay_type']] : '未知支付方式',
            'attribute_type' => $order['attribute_type'],
            'attribute_type_text' => isset($attributeTypeMap[$order['attribute_type']]) ? $attributeTypeMap[$order['attribute_type']] : '未知商品类型',
            'createtime' => date('Y-m-d H:i:s', $order['createtime']),
            'paytime' => $order['pay_time'] ? date('Y-m-d H:i:s', $order['pay_time']) : '',
            'deliverytime' => $order['delivery_time'] ? date('Y-m-d H:i:s', $order['delivery_time']) : '',
            'receipttime' => $order['receipt_time'] ? date('Y-m-d H:i:s', $order['receipt_time']) : '',
            'remark' => $order['remark'],
            'receiver' => $receiver,
            'items' => $orderItems
        ];
        
        $this->success('获取成功', $result);
    }
    
    /**
     * 验证支付方式是否符合商品类型要求
     * @param int $attributeType 商品类型 1=权益商品 2=积分商品 3=助农商品
     * @param int $payType 支付类型 1=微信 2=支付宝 3=聚合支付 4=权益积分 5=绿色积分
     */
    private function validatePaymentType($attributeType, $payType)
    {
        // 定义支付类型常量
        $PAY_WECHAT = 1;      // 微信支付
        $PAY_ALIPAY = 2;      // 支付宝支付
        $PAY_AGGREGATE = 3;   // 聚合支付
        $PAY_EQUITY_POINTS = 4;   // 权益积分支付
        $PAY_GREEN_POINTS = 5;    // 绿色积分支付
        
        switch ($attributeType) {
            case 1: // 权益商品
                // 只支持微信、支付宝、聚合支付
                if (!in_array($payType, [$PAY_WECHAT, $PAY_ALIPAY, $PAY_AGGREGATE])) {
                    $this->error('权益商品只支持微信、支付宝、聚合支付方式');
                }
                break;
                
            case 2: // 积分商品
                // 只支持绿色积分支付
                if ($payType != $PAY_GREEN_POINTS) {
                    $this->error('积分商品只支持绿色积分支付方式');
                }
                break;
                
            case 3: // 助农商品
                // 支持微信、支付宝、聚合、权益积分
                if (!in_array($payType, [$PAY_WECHAT, $PAY_ALIPAY, $PAY_AGGREGATE, $PAY_EQUITY_POINTS])) {
                    $this->error('助农商品支持微信、支付宝、聚合支付、权益积分支付方式');
                }
                break;
                
            default:
                $this->error('无效的商品类型');
        }
    }

    
}